package com.prothink.threadproject.zuoye;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketSale {
    private int tickets = 1000; // 总票数
    private final Lock lock = new ReentrantLock(); // 锁对象

    public static void main(String[] args) {
        TicketSale ticketSale = new TicketSale();
        // 创建包含10个线程的线程池（对应10个售票窗口）
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        // 每个线程模拟一个售票窗口
        for (int i = 0; i < 10; i++) {
            executorService.execute(ticketSale::sellTicket);
        }

        // 关闭线程池
        executorService.shutdown();
    }

    // 售票方法
    public void sellTicket() {
        while (true) {
            lock.lock(); // 获取锁
            try {
                if (tickets > 0) {
                    System.out.println(Thread.currentThread().getName() + " 卖出了1张票，剩余票数：" + (--tickets));
                } else {
                    break; // 票卖完，结束
                }
            } finally {
                lock.unlock(); // 释放锁
            }

            // 模拟售票间隔
            try {
                Thread.sleep(10); // 假设每次售票需要10毫秒
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 恢复中断状态
            }
        }
    }
}
